from django.shortcuts import render
from django.http import HttpResponse
from .models import UserInfo,Root
import json
from myproject.responseMessage import responseType
import jwt
import base64

def add_user(request):
    user = UserInfo()
    root = Root()
    body = request.body
    userInfo = UserInfo.objects.filter(user_name=request.POST.get('user_name'))
    if userInfo.count() == 0:
        user.user_nickname = request.POST.get('user_nickname')
        user.user_name = request.POST.get('user_name')
        user.user_psd = request.POST.get('user_psd')
        user.user_mail = request.POST.get('user_mail')
        user.root_id = Root.objects.get(name = '普通用户').id
        user.save()
        return HttpResponse(json.dumps(responseType.success("恭喜你，注册成功",{})))
    else:
        return HttpResponse(json.dumps(responseType.error("用户已存在")))
    
def login_user(request):
    body = request.body
    try:
        UserInfo.objects.get(user_name=request.POST.get('user_name'))
        try:
            userList = UserInfo.objects.get(user_name=request.POST.get('user_name'),user_psd=request.POST.get('user_psd'))
            return HttpResponse(json.dumps(responseType.success("恭喜你，登陆成功",{
                "userName":userList.user_name,
                "nickname":userList.user_nickname
            })))
        except :
            return HttpResponse(json.dumps(responseType.error("密码错误")))
    except :
        return HttpResponse(json.dumps(responseType.error("用户不存在")))
    

    # if userList.count() == 0:
    #     return HttpResponse(json.dumps(responseType.error("用户不存在")))
    # else:
    #     user_info = userList.values('user_psd')
    #     if user_info[0]['user_psd'] == request.POST.get('user_psd'):
    #         return HttpResponse(json.dumps(responseType.success("恭喜你，登陆成功",{
    #             "userName":userList
    #         })))
    #     else:
    #         return HttpResponse(json.dumps(responseType.error("密码错误")))
    